package dao.User;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import model.User;
import abstractFactory.Factory;

public class UserDAOJPA implements UserDAO{
	static EntityManager manager;

	public EntityManager getManager() {
		if(manager == null) {
			manager = Factory.getFactory().createEntityManager();
		}
		return manager;
	}

	public boolean save(User user){
		getManager().getTransaction().begin();			
		getManager().persist(user);
		getManager().getTransaction().commit();
		return true;
	}

	public boolean update(User user){
		getManager().getTransaction().begin();
		getManager().merge(user);
		getManager().getTransaction().commit();
		return true;
	}

	public boolean delete(User user){
		getManager().getTransaction().begin();
		User u = getManager().find(User.class, user.getId());
		getManager().remove(u);
		getManager().getTransaction().commit();		
		return true;
	}

	public List<User> getAllUsers(){
		Query query = (Query) getManager().createQuery("SELECT u FROM User u where u.active = 1" );
		@SuppressWarnings("unchecked")
		List<User> users = query.getResultList();
		return users;
	}
	public Long getTotalUsers(){
		Query query = (Query) getManager().createQuery("SELECT count(u) FROM User u where u.active = 1" );
		Long total = (Long) query.getSingleResult();
		return total;
	}
	public User doLogin(String userName, String userPassword){
		try {
			Query query = (Query) getManager().createQuery("SELECT u FROM User u where u.login = :n and u.password = :p" );
			query.setParameter("n", userName);
			query.setParameter("p", userPassword);
			User user = (User) query.getSingleResult();
			if(user != null)
				return user;
			else
				return null;
		} 
		catch (Exception e) {	
			return null;				
		}
	}

	public User getUserById(int userId){
		User user = getManager().find(User.class, userId);
		return user;
	}
}
